<script setup lang="ts">
/** global QC */
import { bindMobile, loginByQQ } from '@/services/user'
import { onMounted, ref } from 'vue'
import { mobileRules, codeRules } from '@/utils/rules'
import { showFailToast, showSuccessToast } from 'vant'

import { useLoginSuccess, useMobileCode } from '@/composable'
// 1.进行登录
// 1.1 通过QQ的js文件提过的API获取你登录后的openId(就是登录后的标识)
// 1.2 如果后台的数据库中存储了 openId + 你的手机号 去登录就可以成功,否则失败

// 2.绑定手机
// 2.1 记录两个数据 openId isBind(是否需要绑定QQ)
const openId = ref('')
const isBand = ref(false)
onMounted(() => {
  if (window.QC.Login.check()) {
    // 说明QQ已登录过
    window.QC.Login.getMe((id: string) => {
      console.log('openId', id)
      openId.value = id
      // 进行登录
      loginByQQ(id)
        .then((res) => {
          showSuccessToast('登录成功')
          loginSuccess(res)
        })
        .catch(() => {
          showFailToast('未绑定手机号码')
          isBand.value = true
        })
    })
  }
})
// 获取短信验证码
const mobile = ref('')
const { form, send, time, code } = useMobileCode(mobile, 'bindMobile')
const loginSuccess = useLoginSuccess()
// submit提交表单——绑定手机号逻辑:1.发请求2.处理成功后的逻辑
const bind = async () => {
  // 校验成功后,进入
  try {
    const res = await bindMobile({
      mobile: mobile.value,
      code: code.value,
      openId: openId.value
    })
    loginSuccess(res)
    showSuccessToast('绑定手机号成功')
  } catch (error) {
    showFailToast('绑定手机号失败,' + error)
  }
}
</script>

<template>
  <!-- 没绑定手机号 才显示该组件 -->
  <div class="login-page" v-if="isBand">
    <cp-nav-bar></cp-nav-bar>
    <div class="login-head">
      <h3>手机绑定</h3>
    </div>
    <van-form autocomplete="off" ref="form" @submit="bind">
      <van-field
        name="mobile"
        :rules="mobileRules"
        v-model="mobile"
        placeholder="请输入手机号"
      ></van-field>
      <van-field
        name="code"
        v-model="code"
        :rules="codeRules"
        placeholder="请输入验证码"
      >
        <template #button>
          <span class="btn-send" @click="send">{{
            time > 0 ? `${time}秒后发送` : '发送验证码'
          }}</span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button
          style="margin-top: 50px"
          block
          round
          type="primary"
          native-type="submit"
        >
          立即绑定
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="scss" scoped>
@import '@/styles/login.scss';
</style>
